<!-- 角色编辑弹窗 -->
<template>
  <div>
    <el-drawer :visible="drawerEditBoolen"
               size="50%"
               :before-close="handleClose"
               ref="drawer">
      <template v-slot:title>
        <span class="hLabel">{{ isUpdate ? '添加消息' : '添加消息' }}</span>
      </template>
      <div class="ele-body">
        <el-card shadow="never">
          <div class="flex-column-between height83">
            <el-form ref="form"
                     :model="form"
                     :rules="rules"
                     label-width="100px">
              <el-form-item label="选择发送方式:"
                            prop="type">
                <el-radio-group v-model="form.type"
                                @input="selectRadio"
                                style="min-width: 700px">
                  <el-radio :label="1"
                            :value="1">全部用户</el-radio>
                  <el-radio :label="2"
                            :value="2">部分用户 </el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="消息标题:"
                            prop="title">
                <el-input clearable
                          type="textarea"
                          resize="none"
                          placeholder="请输入消息标题"
                          v-model="form.title">
                </el-input>
              </el-form-item>
              <el-form-item label="消息内容:"
                            prop="content">
                <tinymce-editor ref="editorRef"
                                :init="editorConfig"
                                v-model="form.content" />
              </el-form-item>

              <el-form-item v-if="form.type == 2"
                            label="选择用户:"
                            prop="uid">
                <div class="flex-start-center">
                  <el-input v-if="form.uid"
                            clearable
                            :disabled="true"
                            v-model="form.uid"
                            placeholder="选择的用户显示在这里" />

                  <el-button type="primary"
                             @click="selectUser()">选择用户</el-button>
                </div>
              </el-form-item>
            </el-form>
            <div class="drawer__footer">
              <el-button round
                         type="plain"
                         @click="handleClose"
                         size="medium">返回</el-button>
              <el-button type="primary"
                         round
                         :loading="loading"
                         size="medium"
                         @click="save">确定</el-button>
            </div>
          </div>
        </el-card>
      </div>
    </el-drawer>

    <Camilist :data="current"
              @uidList="uidListFn"
              :drawerUserListBoolen.sync="drawerUserListBoolen"></Camilist>
    <!-- 图片预览 -->
    <el-image-viewer v-if="viewerVisible"
                     style="z-index: 9999"
                     :on-close="closeViewer"
                     :url-list="imgViewArr" />
  </div>
</template>

<script>
import TinymceEditor from '@/components/TinymceEditor/index.vue';
import ElImageViewer from 'element-ui/packages/image/src/image-viewer';
import Camilist from './Camilist.vue';
// import {
//   userOssSignature,
//   qnyOssSignature
// } from '@/api/creatCenter/material';
// import { storageConfigDetail } from '@/api/storageInfo/index';

// import axios from 'axios';
// import {
//   siteCategoriesInsert,
//   siteCategoriesList,
//   siteCategoriesModify,
//   siteCategoriesDetail
// } from '@/api/serviceManagement/categoriesList';
import { upload } from '@/api/saveImg/index';
import { sendNoticeMessage } from '@/api/config/index'
export default {
  name: 'pictureEdit',
  components: { ElImageViewer, Camilist, TinymceEditor },
  props: {
    drawerEditBoolen: {
      type: Boolean,
      default: false
    },
    // 修改回显的数据
    data: Object
  },
  data () {
    const categoryImage = (rule, value, callback) => {
      console.log(this.form.img);
      if (!this.form.img) {
        callback(new Error('请上传图片'));
      } else {
        callback();
      }
    };
    const DEFAULT_FORM = {
      // 分类名称
      type: 1,
      //   分类图片
      content: '',
      // 排序号
      uid: '',
      title: ''
    };
    return {
      editorConfig: {
        height: 525,
        relative_urls: false,
        convert_urls: false,

        images_upload_handler: async (blobInfo, success) => {
          //  ==================================

          const files = blobInfo.blob();
          // 使用 axios 上传，实际开发这段建议写在 api 中再调用 api
          const param = new FormData();

          param.append('file', files, files.name);

          const res = await upload(param);
          console.log(res.data.url);

          success(res.data.url);

          // });
        }
      },
      storageMode: 2,
      options: [],
      imageUrl: '',
      imgViewArr: [],
      viewerVisible: false,
      // 表单数据
      form: { ...DEFAULT_FORM },
      drawerUserListBoolen: false,
      dialogImageUrl: '',
      fileList: [],
      dialogVisible: false,
      current: null,
      // 表单验证规则
      rules: {
        content: [
          {
            required: true,
            message: '请输入消息内容',
            trigger: 'blur'
          }
        ],

        uid: [
          {
            required: true,
            message: '请选择给那些用户发送消息',
            trigger: 'blur'
          }
        ],
        title: [
          {
            required: true,
            message: '请输入消息标题',
            trigger: 'blur'
          }
        ]
      },
      // 提交状态
      loading: false,
      // 是否是修改
      isUpdate: false,
      showChoose: false
    };
  },
  activated () { },
  methods: {
    selectRadio (e) {
      console.log(e);
      if (e == 1) {
        this.form.uid = '';
      }
    },

    uidListFn (e) {
      console.log(e);
      this.form.uid = e.join(',');
      console.log(this.form.uid);
    },
    selectUser () {
      this.current = this.form.uid
      this.drawerUserListBoolen = !this.drawerUserListBoolen;
      console.log(this.drawerUserListBoolen);
    },
    // 获取存储配置
    // async storageConfig () {
    //   const res = await storageConfigDetail();

    //   // console.log(res.storageMode);

    //   this.storageMode = res?.storageMode;
    // },
    // 关闭查看器
    closeViewer () {
      this.viewerVisible = false;
    },
    // 下载图片
    handleDownload (file) {
      window.open(file.url);
    },
    // 删除图片
    handleRemove () {
      this.fileList = [];
      this.imageUrl = '';
      this.form.img = this.imageUrl;
    },
    //  图片上传个数超过限制
    exceedFn () {
      this.$message({
        message: '图片上传已达到上限,请删除后再上传',
        type: 'warning'
      });
    },
    handlePictureCardPreview () {
      const imgStr = this.imageUrl;
      console.log(imgStr);
      if (imgStr.length) {
        if (imgStr.includes(',')) {
          console.log('字符串中包含逗号');
          // 包含的进行slice(',') 分割

          this.imgViewArr = imgStr.split(',').map((item) => item.trim());
        } else {
          console.log('字符串中不包含逗号');
          this.imgViewArr = imgStr.split();
        }

        this.viewerVisible = true;
      } else {
        this.$message({
          message: '没有上传图片无法进行预览',
          type: 'warning'
        });
      }
    },
    // 关闭抽屉
    handleClose () {
      console.log('查看详情');
      this.$emit('update:drawerEditBoolen', false);
    },
    async handleFileChange (file) {
      this.aliFn(file);
    },
    // 阿里云
    async aliFn (file) {
      this.loading = true;

      let files = file.raw;

      console.log(files);
      // 构建请求参数
      let params = new FormData();
      console.log(params);

      //   params.append('signature', '132321313');
      params.append('file', files);
      console.log(params);

      //   let config = {
      //     headers: {
      //       'Access-Control-Allow-Origin': '*',
      //       'x-oss-callback-Authorization': getToken()
      //     }
      //   };

      const res = await upload(params);
      //   let result = await axios.post(res.host, param, config);
      //   let url = res.host + '/' + date + suffix;
      console.log(res);
      if (res.code == 0) {
        this.form.img = res.data.url;
        this.loading = false;
      }
      //   this.form.categoryImages = url;
      //   this.imageUrl = url;
      //   this.loading = false;
    },

    /* 保存编辑 */
    save () {
      this.$refs['form'].validate((valid) => {
        if (!valid) {
          return false;
        }
        // if (this.isUpdate) {
        //   this.form.img = this.imageUrl;
        // }
        const data = {
          ...this.form
        };
        console.log(data);
        this.loading = true;


        sendNoticeMessage(data)
          .then((msg) => {
            console.log(msg);
            this.loading = false;
            this.$message.success(msg.message);

            this.handleClose();
            this.$emit('done');
          })
          .catch((e) => {
            this.loading = false;
            this.$message.error(e.message);
          });
      });
    }
    /* 更新visible */
  },
  watch: {
    drawerEditBoolen (visible) {
      this.$nextTick(() => {
        if (visible) {
          console.log(this.data);
          if (this.data) {
            this.form.id = '';
            this.$util.assignObject(this.form, {
              ...this.data
            });
            if (this.form.img) {
              this.imageUrl = this.form.img;
              let markIndex = this.form.img.lastIndexOf('.');
              let suffix = this.form.img.substring(markIndex);
              if (!this.fileList.length) {
                this.fileList.push({
                  name: suffix,
                  url: this.form.img
                });
              } else {
                this.fileList = [
                  {
                    name: suffix,
                    url: this.form.img
                  }
                ];
              }
            } else {
              this.fileList = [];
            }
            this.isUpdate = true;
          } else {
            this.isUpdate = false;
          }
        } else {
          this.$nextTick(() => {
            this.$refs['form'].resetFields();
            console.log(this.form);
          });
          this.fileList = [];
        }
      });
    }
  }
};
</script>

<style lang="less" scoped>
/*隐藏input（type=number)右边的小箭头*/
/deep/.delInput input::-webkit-outer-spin-button,
/deep/.delInput input::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
}
/deep/.delInput input[type='number'] {
  -moz-appearance: textfield;
}
.foodsDiv div {
  margin-left: 20px;
  margin-top: 10px;
}
.height83 {
  height: 83vh;
}
.hLabel {
  margin: 10px 0 20px;
  font-weight: 700;
  &::before {
    content: '';
    display: inline-block;
    vertical-align: top;

    margin-right: 5px;
    height: 23px;
    width: 6px;
    background-color: #1e6ceb;
  }
}
.drawer__footer {
  display: flex;
  justify-content: flex-start;
  margin-left: 15px;
}
</style>
